# app/models/direct_chat.py
from app import db
from datetime import datetime

class DirectChat(db.Model):
    __tablename__ = 'direct_chats'

    chat_id = db.Column(db.String(36), primary_key=True)
    user1_id = db.Column(db.String(36), db.ForeignKey('users.user_id'), nullable=False)
    user2_id = db.Column(db.String(36), db.ForeignKey('users.user_id'), nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    server_source = db.Column(db.String(36), db.ForeignKey('servers.server_id'))

    user1 = db.relationship('User', foreign_keys=[user1_id], back_populates='direct_chats_user1')
    user2 = db.relationship('User', foreign_keys=[user2_id], back_populates='direct_chats_user2')
    server_source_rel = db.relationship('Server', back_populates='direct_chats')
    messages = db.relationship('Message', back_populates='direct_chat')

    # 确保用户ID有序存储（user1_id < user2_id）
    def __init__(self, **kwargs):
        if 'user1_id' in kwargs and 'user2_id' in kwargs:
            # 保证user1_id总是较小值
            u1, u2 = sorted([kwargs['user1_id'], kwargs['user2_id']])
            kwargs['user1_id'], kwargs['user2_id'] = u1, u2
        super().__init__(**kwargs)

    def __repr__(self):
        return f'<DirectChat {self.user1.username} and {self.user2.username}>'